﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace EPE.WPF
{
    /// <summary>
    /// UCPrinter.xaml 的交互逻辑
    /// </summary>
    public partial class UCPrinter : UserControl
    {
        public UCPrinter()
        {
            InitializeComponent();
            PrintDocument print = new PrintDocument();
            foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
            {
                lstPrinter.Items.Add(sPrint);
            }
            string strDefaultPrinter = ConfigurationManager.AppSettings["DefaultPrinter"];
            this.lblPrintName.Content = strDefaultPrinter;
        }

        private void lstPrinter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //this.PrinterName=this.lstPrinter.SelectedItem.ToString();
            this.lblPrintName.Content = this.lstPrinter.SelectedItem.ToString();
            UpdateAppConfig("DefaultPrinter", this.lstPrinter.SelectedItem.ToString());
            //this.Close();
        }

        ///<summary>  
        ///在＊.exe.config文件中appSettings配置节增加一对键、值对  
        ///</summary>  
        ///<param name="newKey"></param>  
        ///<param name="newValue"></param>  
        private static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                }
            }

            // Open App.Config of executable  
            Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it  
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            // Add an Application Setting.  
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.  
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.  
            ConfigurationManager.RefreshSection("appSettings");
        } 


    }
}
